<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/26
 * Time: 下午9:42
 */

namespace common\logic;


use yii\db\ActiveQuery;
use common\models\UserModel;
use common\models\MsgCodeModel;
use yii\db\Expression;

class UserLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return UserModel::find();
    }

    public function getListByRole($role)
    {
        $list = $this->_all(['role' => $role]);
    }

    public function getSelfParentCode($referee)
    {
        $user = UserModel::findOne(['id' => $referee]);

        return $this->getParentCode($user);
    }

    public function getParentCode(UserModel $user)
    {
        return sprintf('%s%s_', $user->parent_code, $user->id);
    }

    public function getCountByReferee($referee)
    {
        return $this->getCountByParentCode($this->getSelfParentCode($referee));
    }

    public function getCountByParentCode($parent_code, $role = 0)
    {
        $where = ['like', 'parent_code', $parent_code . '%', false];
        if (!empty($role)) {
            $where = ['and', ['=', 'role', $role], $where];
        }

        return $this->getCount($where);
    }

    public function getSign($noncestr, $timestamp, $url)
    {
        $access_token = '';
        $ticket = '';
        $sign = '';
        $cache = \Yii::$app->cache;
        $data = $cache->get('wx_access_token');


        if ($data === false) {
            $token_url = WX_ACCESS_TOKEN_URL . '?grant_type=client_credential&appid=' . WX_App_Id . '&secret=' . WX_App_Secret;
            $res = $this->getDataWithUrl($token_url, false);

            if (isset($res->access_token)) {
                $access_token = $res->access_token;
                $cache->set('wx_access_token', $access_token, 7000);
            } else {
                $access_token = '';
            }
        } else {
            $access_token = $data;
        }

        if (isset($access_token)) {
            $ticket_url = WX_JS_TICKET_URL . '?access_token=' . $access_token . '&type=jsapi';
            $res = $this->getDataWithUrl($ticket_url, false);

            if ($res->errcode == 0 && isset($res->ticket)) {
                $ticket = $res->ticket;
                $cache->set('wx_ticket', $ticket, 7000);

                //$sign_str='jsapi_ticket='.$ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
                $arrParams = [
                    'jsapi_ticket' => trim($ticket),
                    'noncestr' => trim($noncestr),
                    'timestamp' => trim($timestamp),
                    'url' => urldecode(trim($url)),
                ];

                $strSignParams = "";

                foreach ($arrParams as $key => $item) {
                    $strSignParams .= "$key=$item&";
                }

                $strSignParams = substr($strSignParams, 0, -1);

                $sign = sha1($strSignParams);
            }

            if (isset($sign)) {
                return ['code' => 0, 'sign' => $sign, 'msg' => ''];
            } else {
                return ['code' => 2, 'msg' => '签名生成失败'];
            }
        } else {
            return ['code' => 1, 'msg' => '获取Token发生错误'];
        }
    }



    /**
     * 更新分享合伙人记录次数
     *
     * @param $uid
     *
     * @return bool
     */
    public function updateInviteNum($uid)
    {
        $user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
            self::setError('用户不存在');

            return false;
        }

        $res = UserModel::updateAll(['invite_num' => new Expression(intval(intval($user->invite_num) + 1))], ['id' => $uid]);
        if ($res) {
            return true;
        }

        return false;
    }

    /**
     * 更新分享合伙人页面打开次数
     *
     * @param $uid
     *
     * @return bool
     */
    public function updateInviteOpenNum($uid)
    {
        $user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
            self::setError('用户不存在');

            return false;
        }

        $res = UserModel::updateAll(['invite_open_num' => new Expression(intval(intval($user->invite_open_num) + 1))], ['id' => $uid]);
        if ($res) {
            return true;
        }

        return false;
    }


    /**
     * 绑定推荐人
     *
     * @param $referee
     * @param $uid
     *
     * @return bool
     */
    public function bindReferee($referee, $uid)
    {
        $user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
            self::setError('用户不存在');

            return false;
        }

        if ($this->_bindReferee($referee, $user)) {
            return $user->save();
        }

        return false;
    }


    /**
     * 绑定推荐人
     *
     * @param $referee
     * @param $user
     *
     * @return bool
     */
    private function _bindReferee($referee, UserModel $user)
    {
        if ($referee > 0) {
            $refereeInfo = UserModel::findOne(['id' => $referee]);
            if (!empty($refereeInfo) && in_array($refereeInfo->role, [UserModel::ROLE_PARTNER, 0])) {
                if (!empty($user->referee) && $user->role != 1) {
                    self::setError('该用户已绑定合伙人');

                    return false;
                }
                $user->referee = $referee;
                $parent_code = '';
                if (!empty($refereeInfo->parent_code)) {
                    $parent_code .= $refereeInfo->parent_code;
                }
                $parent_code .= $referee . '_';
                $user->parent_code = $parent_code;
                $user->role = count(explode('_', $user->parent_code)) > 3 ? UserModel::ROLE_USER : UserModel::ROLE_PARTNER;

                return true;
            }
        }
        self::setError('合伙人不存在');

        return false;
    }


    public function getRefereeLevel(UserModel $user)
    {
        $code = explode('_', $user->parent_code . $user->id);

        return count(array_filter($code)) - 1;
    }


    /**
     * @param string $code
     * @param int    $referee 推荐人
     *
     * @return string|array
     */
    public function getWxUserInfo($code, $referee = 0)
    {
        //根据微信的授权code获取token和openid
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . WX_App_Id . '&secret=' . WX_App_Secret . '&code=' . $code . '&grant_type=authorization_code';
        $result = $this->getDataWithUrl($url, false);

        if (isset($result->access_token)) {
            $access_token = $result->access_token;
            $openid = $result->openid;

            //获取微信用户的基本信息
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
            $result = $this->getDataWithUrl($url, false);

            if (isset($result->openid) && isset($result->unionid)) {

                $model = UserModel::findOne(['openid' => $result->openid]);
                if (empty($model)){
                    $model = UserModel::findOne(['union_id' => $result->unionid]);
                }


                $refereeCount = $selfAmount = $otherAmount = $reportCount = $userCount = 0;

                if (!empty($model)) {//注册过
                    
                    $model->union_id = $result->unionid;
                    $model->openid = $result->openid;
                    $model->save();

                    if (($model->role == UserModel::ROLE_PARTNER && empty($model->referee))||$model->role ==UserModel::ROLE_SUPER_PARTNER) {
                        $parentCode =$this->getParentCode($model);
                        $userCount = $this->getCountByParentCode($parentCode);
                        $reportCount = ReportLogic::instance()->getCountByParentCode($parentCode, $model->id);
                        $selfAmount = ReturnLogLogic::instance()->getSumByParentCode($parentCode);
                        $refereeCount = $this->getCountByParentCode($parentCode, UserModel::ROLE_PARTNER);
                        $otherAmount = ReturnLogLogic::instance()->getSumByChildId($model->id);
                    }

                    return [
                        'openid' => $result->openid,
                        'headimgurl' => $result->headimgurl, 
                        'nickname' => $result->nickname, 
                        "mobile" => $model->mobile, 
                        "uid" => $model->id,
                        "role" => $model->role,
                        "parent_code" => $model->parent_code,
                        "referee" => $model->referee,
                        'reportCount' => $reportCount,
                        'userCount' => $userCount,
                        'selfAmount' => $selfAmount,
                        'otherAmount' => $otherAmount,
                        'refereeCount' => $refereeCount,
                        'invite_num' => $model->invite_num,
                        'union_id' =>  $result->unionid,
                        'invite_open_num' => $model->invite_open_num,
                        'redpacket_money' => $model->redpacket_money,
                        'redpacket_num' => $model->redpacket_num,
                        'isgetredpacket' => $model->isgetredpacket];
                } else {//未注册过
                    $model = new UserModel();
                    $model->nickname = $result->nickname;
                    $model->openid = $result->openid;
                    $model->pcopenid = '';
                    $model->union_id = $result->unionid;
                    $model->avatar = $result->headimgurl;
                    $model->mobile = '';
                    $this->_bindReferee($referee, $model);
                    $model->create_time = time();
                    if ($model->save()) {
                        return [
                            'openid' => $result->openid,
                            'headimgurl' => $result->headimgurl,
                            'nickname' => $result->nickname,
                            "mobile" => $model->mobile,
                            "uid" => $model->id,
                            'reportCount' => $reportCount,
                            'userCount' => $userCount,
                            'selfAmount' => $selfAmount,
                            'otherAmount' => $otherAmount,
                            "role" => $model->role,
                            "parent_code" => '',
                            "referee" => 0,
                            'invite_num' => 0,
                            'invite_open_num' => 0,
                            'redpacket_money' => 0,
                        	'redpacket_num' => 0,
                        	'isgetredpacket' => 0
                        ];

                    } else {
                        return '保存失败';
                    }
                }
            } else {
                return $result->errmsg;
            }
        } else {
            return $result->errmsg;
        }
    }

    public function getUserInfo($uid)
    {
        $model = UserModel::findOne(['id' => $uid]);
        $refereeCount = $selfAmount = $otherAmount = $reportCount = $userCount = 0;
        if (!empty($model)) {//注册过

            if (in_array( $model->role,  [UserModel::ROLE_PARTNER,0]) || !empty($model->referee)) {
                $parentCode =$this->getParentCode($model);
                $userCount = $this->getCountByParentCode($parentCode);
                $reportCount = ReportLogic::instance()->getCountByParentCode($parentCode, $model->id);
                $selfAmount = ReturnLogLogic::instance()->getSumByUid($uid);
                $refereeCount = $this->getCountByParentCode($parentCode, UserModel::ROLE_PARTNER);
                $otherAmount = ReturnLogLogic::instance()->getSumByChildId($model->id);
            }

            return [
                'headimgurl' => $model->avatar, 'nickname' => $model->nickname, "mobile" => $model->mobile, "uid" => $model->id,
                "role" => $model->role,
                "openid" => $model->openid,
                "parent_code" => $model->parent_code,
                "referee" => $model->referee,
                'reportCount' => $reportCount,
                'userCount' => $userCount,
                'selfAmount' => $selfAmount,
                'otherAmount' => $otherAmount,
                'refereeCount' => $refereeCount,
                'invite_num' => $model->invite_num,
                'invite_open_num' => $model->invite_open_num,
                'redpacket_money' => $model->redpacket_money,
                'redpacket_num' => $model->redpacket_num,
                'isgetredpacket' => $model->isgetredpacket
            ];
        }

        return false;
    }

    public function test()
    {

    }


    public function bindMobile($mobile, $sms_code, $uid, $referee)
    {
        $rlt = MsgCodeModel::findOne(["uid" => $uid, "mobile" => $mobile, "code" => $sms_code]);

        if (!empty($rlt)) {
            if ($rlt->create_time > (time() - 10 * 60)) {
                $refereeUser = UserModel::findOne(['id' => $referee]);//兼容$referee=-1的情况

                //绑定手机号到用户表
                $user = UserModel::findOne(["id" => $uid]);
                $parent_code='';
                if (!empty($refereeUser)) {
                    $parent_code = explode('_', $refereeUser->parent_code);
                    $parent_code = array_filter($parent_code);
                }
                $user->mobile = $mobile;

                if (count($parent_code) > 0) {
                    if (!empty($refereeUser)) {
                        $user->referee = $referee;
                        $user->parent_code = $refereeUser->parent_code . $referee . '_';
                    }
                }
                if ($user->save()) {
                    MsgCodeModel::deleteAll(["uid" => $uid, "mobile" => $mobile, "code" => $sms_code]);
                    return ['code' => 0, 'msg' => '绑定成功'];
                } else {
                    return ['code' => 2, 'msg' => '绑定失败'];
                }

            } else {
                return ['code' => 3, 'msg' => '验证码超时'];
            }

        } else {
            return ['code' => 1, 'msg' => '验证码不正确'];
        }
    }


    public function sendMsg($mobile, $uid)
    {
        if (isset($mobile) && strlen($mobile) == 11) {
            //确认60s内该手机号有没有发送过短信
            $rlt = MsgCodeModel::find()->where(['and', "mobile=" . $mobile, "create_time>" . (time() - 60)])->one();
            if (!$rlt) {
                $timeout = 15;
                $msg_code = $this->randomKeys(6);

                $url = Msg_Url;
                $post_data = ["apikey" => Msg_Key, "mobile" => $mobile, "text" => "您的验证码是" . $msg_code . "。如非本人操作，请忽略本短信"];
                $res = $this->getDataWithUrl($url, true, $post_data);

                if ($res && $res->code == 0) {
                    //先删除该号码之前的所有发送记录
                    MsgCodeModel::deleteAll(["mobile" => $mobile]);
                    $model = new MsgCodeModel();
                    $model->uid = $uid;
                    $model->code = $msg_code;
                    $model->mobile = $mobile;
                    $model->create_time = time();
                    if ($model->save()) {
                        $res = ["code" => 0, "msg" => $res->msg, "sms_code" => $msg_code, "msg" => "保存数据失败"];
                    } else {
                        $res = ["code" => 1, "msg" => "保存数据失败"];
                    }
                } else {
                    $res = ["code" => 2, "msg" => "验证码发送失败，请稍后再试"];
                }

                return $res;
            } else {
                return ["code" => 3, "msg" => "验证码获取太频繁，请稍后再试"];
            }
        } else {
            return ["code" => 4, "msg" => "发送失败，非法手机号"];
        }
    }

    public function randomKeys($length)
    {
        $pattern = '1234567890';
        $key = '';
        for ($i = 0; $i < $length; $i++) {
            $key .= $pattern{mt_rand(0, 9)};    //生成php随机数
        }

        return $key;
    }

    //超级合伙人看到的一级、二级合伙人列表
    public function getPartnerByGrade($uid, $grade ,$page, $pageSize = 20)
    {
        $nextPage = 0;
        $query = $this->_getActiveQuery();

        $offset = ($page - 1) * $pageSize;
        $grade_one_count=0;
        $grade_two_count=0;

        $grade_one_count=$query->select(['id'])->where(['role'=>2,'referee'=>$uid.'_'])->count();
        $grade_two_count=$query->select(['id'])->where(['role'=>2])->andWhere(['<>','referee',$uid])->andWhere(['like','parent_code',$uid.'_'])->count();

        if(intval($grade)==1){
            $query->select(['id', 'nickname', 'avatar','mobile', 'create_time'])->limit($pageSize+1)->where(['role'=>2,'referee'=>$uid.'_'])->offset($offset)->orderBy(['id'=>SORT_DESC]);
        }
        else{
            $query->select(['id', 'nickname', 'avatar','mobile', 'create_time'])->limit($pageSize+1)->where(['role'=>2])->andWhere(['<>','referee',$uid])->andWhere(['like','parent_code',$uid.'_'])->offset($offset)->orderBy(['id'=>SORT_DESC]);
        }

        $data = $query->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }
        $result = [];

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $result[] = [
                    'id' => $v['id'],
                    'create_time' => date('Y-m-d', $v['create_time']),
                    'nickname' => $v['nickname'],
                    'avatar' => $v['avatar'],
                    'mobile' => $v['mobile']
                ];
            }
        }

        return ['nextPage' => $nextPage, 'list' => $result,'grade_one_count'=>$grade_one_count,'grade_two_count'=>$grade_two_count];
    }

    //超级合伙人看到的他发展的注册用户
    public function getUsersByPartner($uid ,$page, $pageSize = 20)
    {
        $nextPage = 0;
        $query = $this->_getActiveQuery();

        $offset = ($page - 1) * $pageSize;
        $query->select(['id', 'nickname', 'avatar','mobile', 'create_time'])->limit($pageSize+1)->where(['like','parent_code',$uid.'_'])->offset($offset)->orderBy(['id'=>SORT_DESC]);

        $data = $query->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }
        $result = [];

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $result[] = [
                    'id' => $v['id'],
                    'create_time' => date('Y-m-d', $v['create_time']),
                    'nickname' => $v['nickname'],
                    'avatar' => $v['avatar'],
                    'mobile' => $v['mobile']
                ];
            }

        }

        return ['nextPage' => $nextPage, 'list' => $result];
    }


    //超级合伙人看到的他发展用户的报备数据
    public function getReportsByPartner($uid ,$page, $pageSize = 20)
    {
        $nextPage = 0;
        $db = \Yii::$app->db;

        $offset = ($page - 1) * $pageSize;
        $data = $db->createCommand('SELECT `a`.`contacts`, `a`.`phone`, `a`.`status`, `a`.`sign`, `a`.`create_time`, `b`.`house_name`, `c`.`nickname`, `c`.`parent_code` FROM `ph_user` `c` RIGHT JOIN `ph_report` `a` ON a.referee=c.id LEFT JOIN `ph_house` `b` ON a.house_id=b.id WHERE `c`.`parent_code` LIKE \'%'.$uid.'\\_%\' or a.referee='.$uid.' ORDER BY `a`.`id` DESC LIMIT '.($pageSize+1))->queryAll();
//        $query->select(['a.contacts as nickname','a.phone as mobile','a.status as status','a.referee','a.create_time','b.house_name','c.nickname','c.parent_code'])->alias('c')->rightJoin('ph_report a','a.referee=c.id')->leftJoin('ph_house b','a.house_id=b.id')->where(['like','c.parent_code',$uid.'_'])->limit($pageSize+1)->offset($offset)->orderBy(['a.id'=>SORT_DESC]);
//        $data = $query->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }

        $result = [];
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $result[] = [
                    'house_name'=>$v['house_name'],
                    'partner'=>$v['nickname'],
                    'contacts' => $v['contacts'],
                    'create_time' => date('Y-m-d H:i', $v['create_time']),
                    'phone' => $v['phone'],
                    'status' => $v['status'],
                    'sign' => $v['sign']
                ];
            }

        }

        return ['nextPage' => $nextPage, 'list' => $result];
    }
    
    //编辑用户信息
    public function editUserinfo($uinfo){
    	$uid = $uinfo['id'];
    	
    	$user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
            self::setError('用户不存在');

            return false;
        }		
        $user->nickname = $uinfo['nickname'];
        $user->avatar = $uinfo['avatar'];
        $user->mobile = $uinfo['mobile'];
        
		$res = $user->save();
        if ($res) {
            return true;
        }
        return false;
    }


    public function MobileLogin($mobile, $sms_code, $uid, $referee)
    {
        $rlt = MsgCodeModel::findOne(["uid" => $uid, "mobile" => $mobile, "code" => $sms_code]);

        if (!empty($rlt)) {
            if ($rlt->create_time > (time() - 10 * 60)) {
                return ['code' => 'ok', 'msg' => '登录成功'];

            } else {
                return ['code' => 3, 'msg' => '验证码超时'];
            }
        } else {
            return ['code' => 1, 'msg' => '验证码不正确'];
        }
    }

    //pc授权登录
    public function GetPcSign($code,$phone = ''){

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' .WX_PcApp_Id. '&secret=' .WX_PcApp_Secret. '&code=' .$code. '&grant_type=authorization_code';
        $result = $this->getDataWithUrl($url, false);
        

        if (isset($result->access_token)) {
            $access_token = $result->access_token;
            $openid = $result->openid;

            //获取微信用户的基本信息
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
            $result = $this->getDataWithUrl($url, false);
            // return $result;

            if (isset($result->unionid)) {
                $model = UserModel::findOne(['union_id' => $result->unionid]);
                $refereeCount = $selfAmount = $otherAmount = $reportCount = $userCount = 0;

                if (!empty($model)) {//注册过
                    
                    $model->pcopenid = $result->openid;
                    $model->save();

                    if (($model->role == UserModel::ROLE_PARTNER && empty($model->referee))||$model->role ==UserModel::ROLE_SUPER_PARTNER) {
                        $parentCode =$this->getParentCode($model);

                        $userCount = $this->getCountByParentCode($parentCode);
                        $reportCount = ReportLogic::instance()->getCountByParentCode($parentCode, $model->id);
                        $selfAmount = ReturnLogLogic::instance()->getSumByParentCode($parentCode);
                        $refereeCount = $this->getCountByParentCode($parentCode, UserModel::ROLE_PARTNER);
                        $otherAmount = ReturnLogLogic::instance()->getSumByChildId($model->id);
                    }
                   
                    return [
                        'openid' => $result->openid, 'headimgurl' => $result->headimgurl, 'nickname' => $result->nickname, "mobile" => $model->mobile, "uid" => $model->id,
                        "role" => $model->role,
                        "parent_code" => $model->parent_code,
                        "referee" => $model->referee,
                        'reportCount' => $reportCount,
                        'userCount' => $userCount,
                        'selfAmount' => $selfAmount,
                        'otherAmount' => $otherAmount,
                        'refereeCount' => $refereeCount,
                        'invite_num' => $model->invite_num,
                        'invite_open_num' => $model->invite_open_num,
                        'code'=>'ok'];
                } else {//未注册过
                    $model = new UserModel();
                    $model->nickname = $result->nickname;
                    $model->openid = '';
                    $model->pcopenid = $result->openid;
                    $model->union_id = $result->unionid;
                    $model->avatar = $result->headimgurl;
                    $model->mobile = $phone;
                    $referee = '0';
                    $this->_bindReferee($referee, $model);
                    $model->create_time = time();

                    if ($model->save()) {
                        return [
                            'openid' => $result->openid,
                            'union_id'=>$result->unionid,
                            'headimgurl' => $result->headimgurl,
                            'nickname' => $result->nickname,
                            "mobile" => $model->mobile,
                            "uid" => $model->id,
                            'reportCount' => $reportCount,
                            'userCount' => $userCount,
                            'selfAmount' => $selfAmount,
                            'otherAmount' => $otherAmount,
                            "role" => $model->role,
                            "parent_code" => '',
                            "referee" => 0,
                            'invite_num' => 0,
                            'invite_open_num' => 0,
                            'code'=>'ok'
                        ];

                    } else {
                        return ['code'=>'-1','err'=>'保存失败'];
                    }
                }
            } else {
                // return $result->errmsg;
                return ['code'=>'-2','err'=>$result->errmsg];
            }
        } else {
            // return $result->errmsg;
                return ['code'=>'-3','err'=>$result->errmsg];
        }

    }

}

